package it.infodea.tapestrydea.services;

import it.infodea.tapestrydea.services.jcr.JcrAssetStreamer;

import java.io.IOException;

import javax.jcr.PathNotFoundException;
import javax.jcr.RepositoryException;

import org.apache.tapestry5.internal.services.RequestConstants;
import org.apache.tapestry5.ioc.internal.util.TapestryException;
import org.apache.tapestry5.services.Dispatcher;
import org.apache.tapestry5.services.Request;
import org.apache.tapestry5.services.Response;

/**
 * Questo dispatcher di occupa di convogliare tutte le richieste per il
 * repository convertendo le url del tipo asset/jcr/folder/file.ext verso la
 * reale risorsa memorizzata nel repository
 * 
 * @author rob
 * 
 */
public class RepositoryAssetDispatcher implements Dispatcher {

	// il prefisso per il repository, una url per esempio potrebbe essere
	// @Path("asset/jcr/folder1/folder1_1/file.ext")
	public static final String REPOSITORY_PATH_PREFIX = RequestConstants.ASSET_PATH_PREFIX + "jcr";

	//per effettuare lo streaming verso il client
	private final JcrAssetStreamer streamer;

	public RepositoryAssetDispatcher(JcrAssetStreamer streamer) {
		this.streamer = streamer;
	}

	public boolean dispatch(Request request, Response response) throws IOException {
		String path = request.getPath();
		if (!isJcrRequest(path)) {
			return false;
		}
		try {
			String clientData = getJcrResourcePath(path);
			streamer.streamJcrAsset(clientData);
		} catch (PathNotFoundException e) {
			throw new TapestryException(e.getMessage(), e);
		} catch (RepositoryException e) {
			throw new TapestryException(e.getMessage(), e);
		}
		return true;
	}

	public static String getJcrResourcePath(String path) {
		return path.substring(REPOSITORY_PATH_PREFIX.length());
	}

	public static boolean isJcrRequest(String path) {
		return path.startsWith(REPOSITORY_PATH_PREFIX);
	}

}
